# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import hashlib
import random
import execjs

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
喜马拉雅-音频地址获取
"""

class Test_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15'
        }


    def get_contents(self, albumId, pageNum, sort, pageSize):
        # 先调用该方法获取xm-sign
        self.getSign1(self.getServerTime())
        url = "https://www.ximalaya.com/revision/play/v1/audio?id=192414498&ptype=1"
        response = requests.get(url, headers=self.headers)
        infos = json.loads(response.text)
        return infos


    def getServerTime(self):
        """
        获取喜马拉雅服务器的时间戳
        :return:
        """
        # 这个地址就是返回服务器时间戳的接口
        serverTimeUrl = "https://www.ximalaya.com/revision/time"
        response = requests.get(serverTimeUrl,headers = self.headers)
        return response.text

    def getSign(self,serverTime):
        """
        生成 xm-sign
        规则是 md5(ximalaya-服务器时间戳)(100以内随机数)服务器时间戳(100以内随机数)现在时间戳
        :param serverTime:
        :return:
        """
        nowTime = str(round(time.time()*1000))

        sign = str(hashlib.md5("ximalaya-{}".format(serverTime).encode()).hexdigest()) + "({})".format(str(round(random.random()*100))) + serverTime + "({})".format(str(round(random.random()*100))) + nowTime
        # 将xm-sign添加到请求头中
        self.headers["xm-sign"] = sign
        # return sign

    '''生成xm-sign'''
    def getSign1(self, serverTime):
        #读取同一路径下的js文件
        with open('xmSign.js', encoding='utf-8') as f:
            js = f.read()

        # 通过compile命令转成一个js对象
        docjs = execjs.compile(js)
        # 调用js的function
        res = docjs.call('python',serverTime)
        #res = docjs.call('getnow')
        self.headers["xm-sign"] = res
        return res


if __name__ == '__main__':
    test_get = Test_Get()
    test_get.get_contents('3544633','1','1','30')